# -*- coding: utf-8 -*-
from django.core.handlers.wsgi import WSGIRequest

from firstDjango.decorators import dump_form_data, get, post
from index.service import comment_service
from index.protocol.comment_protocol import FetchMyCommentsRequest, UpdateCommentRequest
from silk.profiling import profiler

@dump_form_data
def publish_comment(request: WSGIRequest):
    form_data = getattr(request, 'form_data', None)
    book_id = form_data.get('book_id')
    score = form_data.get('rate')
    content = form_data.get('content')
    user_id = request.session.get('user').id
    comment_service.add_comment(user_id, book_id, score, content)
    return "ok"


@dump_form_data
def delete_comment(request: WSGIRequest):
    form_data = getattr(request, 'form_data', None)
    user_id = request.session.get('user').id
    comment_id = form_data.get('comment_id')
    comment_service.delete_comment(user_id, comment_id)
    return "ok"


def fetch_comments(req: WSGIRequest):
    form_data = req.GET
    book_id = int(form_data.get('book_id'))
    page = int(form_data.get('page', 1))
    page_size = int(form_data.get('page_size', 10))
    user = req.session.get('user')
    current_user_id = user.id if user else None
    order_by = form_data.get('order_by', "like_count")

    total_count, comments = comment_service.fetch_comments(
        req, page, page_size, order_by=order_by, book_id=book_id, current_user_id=current_user_id
    )
    return {
        "total_count": total_count,
        "page": page,
        "page_size": page_size,
        "comments": comments
    }


@get(request_data_class=FetchMyCommentsRequest)
def fetch_my_comments(req: WSGIRequest, data: FetchMyCommentsRequest):
    user = req.session.get('user')
    user_id = user.id
    total_count, comments = comment_service.fetch_comments(
        req, data.page, data.page_size, order_by=data.order_by, user_id=user_id, current_user_id=user_id
    )
    return {
        "total_count": total_count,
        "page": data.page,
        "page_size": data.page_size,
        "comments": comments
    }


@post(request_data_class=UpdateCommentRequest)
def update(req: WSGIRequest, comment: UpdateCommentRequest):
    user_id = req.session.get("user").id
    comment_service.update(user_id, comment.comment_id, comment.rate, comment.content)
